package action.user;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import option.OperationEnum;

import org.apache.log4j.Logger;

import service.UserService;
import util.MD5Util;
import entity.User;

/**
 *登录相关
 */
@SuppressWarnings("serial")
public class LogInOutServlet extends HttpServlet{
	private static Logger log = Logger.getLogger(LogInOutServlet.class);
	
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = (String) request.getAttribute("action");
		if (action.equals(OperationEnum.USER_TOLOGINFORM.getValue())) {//跳转到登录页面
			request.getRequestDispatcher("/WEB-INF/pages/user/login_form.jsp").forward(request, response);
		} else if (action.equals(OperationEnum.USER_LOGIN.getValue())) {//登录
			String email = request.getParameter("email");
			String password = request.getParameter("password");
			String uri = request.getParameter("uri");
			String passwordmd5 = MD5Util.getMD5String(password);
			
			request.setAttribute("email", email);
			try {
				UserService service = new UserService();
				User user = service.queryUserByEmail(email);
				if (user == null) {
					request.setAttribute("errorMsg", "用户不存在");
					request.getRequestDispatcher("/WEB-INF/pages/user/login_form.jsp").forward(request, response);
				} else if (!user.getPasswordmd5().equals(passwordmd5)) {
					request.setAttribute("errorMsg", "密码错误");
					request.getRequestDispatcher("/WEB-INF/pages/user/login_form.jsp").forward(request, response);
				} else {
					//记录用户最后登录ip和时间
					String ip = request.getRemoteAddr();
					user.setLast_login_ip(ip);
					user.setLast_login_time(new Date());
					try {
						service.updateUser(user);
					} catch (Exception e1) {
						log.error("记录用户最后登录ip和时间时出错," + e1);
					}
					//将用户信息保存到session对象中
					request.getSession().setAttribute("user", user);
					if (uri != null && !"".equals(uri)) {
						response.sendRedirect(uri);
					} else {
						request.getRequestDispatcher("/WEB-INF/pages/main/main.jsp").forward(request, response);
					}
				}
			} catch (Exception e) {
				log.error("登录时出错," + e);
				request.setAttribute("errorMsg", "系统出现异常");
				request.getRequestDispatcher("/WEB-INF/pages/user/login_form.jsp").forward(request, response);
			}
		} else if (action.equals(OperationEnum.USER_LOGOUT.getValue())) {//退出
			request.getSession().removeAttribute("user");
			request.getRequestDispatcher("/WEB-INF/pages/user/login_form.jsp").forward(request, response);
		}
	}
}
